package com.applink.sell_proof.database.table;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.database.EMarketingContentProvider;
import com.applink.sell_proof.model.Project;

public class ProjectDBHelper {

	private static String TAG = "ProjectDBHelper";

	public static final String TABLE_NAME = "project_table";
	public static final String ID = "id";
	public static final String NAME = "project_name";
	public static final String CUSTOMER_COMPANY_NAME = "customer_company_name";
	public static final String STATUS = "project_status";
	public static final String AMOUNT = "project_amount";
	public static final String UPDATED = "project_updated";
	public static final String NEWINSERT = "project_newinsert";
	public static final String DATE = "project_date";

	public static final String SQL_EXCUTE = "CREATE TABLE " + TABLE_NAME + "("
			+ ID + " integer default 0 ," + NAME + " text default '' ,"
			+ CUSTOMER_COMPANY_NAME + " text default '' ," + STATUS
			+ " text default '' ," + AMOUNT + " integer default 0 ," + UPDATED
			+ " integer default 1 ," + NEWINSERT + " integer default 0 ,"
			+ DATE + " integer default 0 " + ");";

	public static String insertUpdateProject(Project p) {
		return insertUpdateProject(p, true);
	}

	public static void deleteDataProject() {
		// ContentValues values = new ContentValues();
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();
		resolver.delete(EMarketingContentProvider.PROJECT_CONTENT_URI, null,
				null);
	}

	/**
	 * 
	 * insert/update a project with it associate update status
	 * 
	 * @param p
	 * @param isUpdated
	 * @return
	 */
	public static String insertUpdateProject(Project p, boolean isUpdated) {

		ContentValues values = new ContentValues();
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		String id = p.getId();

		if (id.equals(""))
			id = UUID.randomUUID().toString();

		values.put(ID, id);

		if (p.isUpdated(NAME))
			values.put(NAME, p.getName());

		if (p.isUpdated(CUSTOMER_COMPANY_NAME))
			values.put(CUSTOMER_COMPANY_NAME, p.getCustomerCompanyName());

		if (p.isUpdated(STATUS))
			values.put(STATUS, p.getStatus());

		if (p.isUpdated(AMOUNT))
			values.put(AMOUNT, p.getAmount());

		if (p.isUpdated(DATE))
			values.put(DATE, p.getDate());

		values.put(UPDATED, isUpdated ? 1 : 0);

		Log.i(TAG, id + " : created");

		// if this is an update
		if (resolver.update(EMarketingContentProvider.PROJECT_CONTENT_URI,
				values, ID + "=?", new String[] { id }) == 1)
			return id;

		if (p.isNewInsert())
			values.put(NEWINSERT, 1);

		resolver.insert(EMarketingContentProvider.PROJECT_CONTENT_URI, values);
		return id;
	}

	public static void syncedDone(String Id) {

		if (Id.equals(""))
			return;

		ContentValues values = new ContentValues();
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		values.put(UPDATED, 1);
		values.put(NEWINSERT, 0);

		resolver.update(EMarketingContentProvider.PROJECT_CONTENT_URI, values,
				ID + "=?", new String[] { Id });

	}

	/**
	 * 
	 * insert list of Projects with the update associate with all of its
	 * 
	 * @param pjList
	 * @param massupdateset
	 */
	public static void insertUpdateProjects(final List<Project> pjList,
			final boolean massupdateset) {
		new Thread() {
			@Override
			public void run() {
				for (Project p : pjList) {
					insertUpdateProject(p, massupdateset);
				}
			}
		}.start();
	}

	public static void insertUpdateProjects(final List<Project> pjList) {
		insertUpdateProjects(pjList, true);
	}

	/**
	 * 
	 * retrieve the project by serverId
	 * 
	 * @param id
	 * @return
	 */
	public static Project getProjectById(String id) {

		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		Cursor cursor = resolver.query(
				EMarketingContentProvider.PROJECT_CONTENT_URI, null, ID + "=?",
				new String[] { id }, null);

		if (cursor != null) {
			try {
				if (cursor.moveToFirst()) {
					Project p = createProjectFromCursor(cursor);
					return p;
				}
			} finally {
				cursor.close();
			}
		}
		return null;
	}

	public static List<Project> searchProjects(String keyword) {
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		Cursor cursor;

		if (keyword.equals(""))
			cursor = resolver.query(
					EMarketingContentProvider.PROJECT_CONTENT_URI, null, null,
					null, null);
		else
			cursor = resolver.query(
					EMarketingContentProvider.PROJECT_CONTENT_URI, null, "("
							+ CUSTOMER_COMPANY_NAME + " LIKE ?) OR (" + NAME
							+ " LIKE ?) OR (" + STATUS + " LIKE ?) OR ("
							+ AMOUNT + " LIKE ?)", new String[] {
							"%" + keyword + "%", "%" + keyword + "%",
							"%" + keyword + "%", "%" + keyword + "%" }, null);

		List<Project> pjs = new ArrayList<Project>();

		if (cursor != null) {
			try {
				while (cursor.moveToNext()) {
					Project p = createProjectFromCursor(cursor);

					pjs.add(p);
				}
			} finally {
				cursor.close();
			}
		}
		return pjs;
	}

	/**
	 * 
	 * get list of projects by one/many status string
	 * 
	 * @param status
	 * @return
	 */
	public static List<Project> getProjectsByStatus(String status) {

		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		// select all rows and
		Cursor cursor = resolver.query(
				EMarketingContentProvider.PROJECT_CONTENT_URI, null, STATUS
						+ " IN (" + status + ")", null, null);

		List<Project> pjs = new ArrayList<Project>();

		if (cursor != null) {
			try {
				while (cursor.moveToNext()) {
					Project p = createProjectFromCursor(cursor);

					pjs.add(p);
				}
			} finally {
				cursor.close();
			}
		}

		return pjs;
	}

	/**
	 * 
	 * get list of projects that are ready for sync with the server
	 * 
	 * @return
	 */
	public static List<Project> getNotUpdatedRecords() {
		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		// select all rows and
		Cursor cursor = resolver.query(
				EMarketingContentProvider.PROJECT_CONTENT_URI, null, UPDATED
						+ "=0", null, null);

		List<Project> pjs = new ArrayList<Project>();

		if (cursor != null) {
			try {
				while (cursor.moveToNext()) {
					Project p = createProjectFromCursor(cursor);

					pjs.add(p);
				}
			} finally {
				cursor.close();
			}
		}
		return pjs;

	}

	/**
	 * Generate Project object from a cursor
	 * 
	 * @param c
	 * @return
	 */
	private static Project createProjectFromCursor(Cursor c) {
		Project p = new Project();

		p.setId(c.getString(c.getColumnIndex(ID)));

		// p.setLocalId(c.getString(c.getColumnIndex(Constant.ID_LOCAL)));

		p.setName(c.getString(c.getColumnIndex(NAME)));
		p.setCustomerCompanyName(c.getString(c
				.getColumnIndex(CUSTOMER_COMPANY_NAME)));
		p.setStatus(c.getString(c.getColumnIndex(STATUS)));
		p.setAmount(c.getInt(c.getColumnIndex(AMOUNT)));
		p.setDate(c.getLong(c.getColumnIndex(DATE)));

		p.setNewInsert((c.getInt(c.getColumnIndex(NEWINSERT)) == 1) ? true
				: false);

		return p;
	}
}
